package cn.just.filter;

import cn.just.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author wujiaming
 */
public class AccessFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws ServletException, IOException {
        //若登录就执行下一步，没有登录就显示登录页面
        //request.getSession没有这个办法，需要将父类类型转型为子类类型
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        System.out.println("user=" + user);
        if(user==null){
            //在过滤其中重定向用绝对路径
            response.sendRedirect(request.getContextPath() + "/ShowLoginServlet");
        }else{
            chain.doFilter(request,response);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
